package com.csii.activiti.server.component.ribbon.callback;

import com.alibaba.fastjson.JSONObject;
import com.csii.activiti.server.abstraction.entity.ActCallbackMessage;
import com.csii.activiti.server.abstraction.entity.ActFlowCallbackResult;
import com.csii.activiti.server.abstraction.service.optional.ActCallbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;


public class ActCloudCallbackServiceImpl implements ActCallbackService {

    @Autowired
    @Qualifier("callbackCloudRestTemplate")
    private RestTemplate callbackCloudRestTemplate;

    private RestTemplate callbackRestTemplate = new RestTemplate();

    @Autowired
    private DiscoveryClient discoveryClient;

    private final String okCode = "200";


    @Override
    public ActFlowCallbackResult callback(ActCallbackMessage callbackMessage, String callbackUrl) {
        ActFlowCallbackResult callbackResult = new ActFlowCallbackResult();
        String resultJson = getResult(callbackMessage, callbackUrl);
        JSONObject jsonObject = JSONObject.parseObject(resultJson);
        Object code = jsonObject.get("code");
        if (code != null && okCode.equals(code.toString())){
            callbackResult.setResult(true);
        }else{
            callbackResult.setResult(false);
            callbackResult.setMessage(JSONObject.toJSONString(resultJson));
        }

        return callbackResult;
    }

    private String getResult(ActCallbackMessage callbackMessage, String callbackUrl){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<ActCallbackMessage> entity = new HttpEntity<>(callbackMessage, headers);
        List<String> services = discoveryClient.getServices();
        try {
            if (services.contains(new URL(callbackUrl).getHost())) {
                return callbackCloudRestTemplate.postForObject(callbackUrl, entity, String.class);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return callbackRestTemplate.postForObject(callbackUrl, entity, String.class);

    }
}
